package cn.edu.zzuli.wechat.listener;


import cn.edu.zzuli.model.dto.JudgeDto;
import cn.edu.zzuli.model.entity.OfferOrder;
import cn.edu.zzuli.wechat.user.mapper.OfferOrderMapper;
import cn.edu.zzuli.wechat.user.mapper.UserMapper;
import cn.edu.zzuli.common.utils.NowDate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * 监听 Redis key 过期事件
 */
@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {


    @Autowired
    private OfferOrderMapper offerOrderMapper;

    @Autowired
    private UserMapper userMapper;

    public RedisKeyExpirationListener(RedisMessageListenerContainer redisMessageListenerContainer) {
        super(redisMessageListenerContainer);
    }

    /**
     * 针对 redis 数据失效事件，进行数据处理
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        //拿到key
        log.info("监听Redis key过期，key：{}", message.toString());

        String key = message.toString();
        if(key != null && key.startsWith("order_")){
            String substring = key.substring(6);
            int oid = Integer.parseInt(substring);
            JudgeDto judgeDto = offerOrderMapper.findAndJudge(oid);
            if(judgeDto.getStatus() != 2 && judgeDto.getStatus() != 6){
                //判断是否是超时订单
                if (NowDate.stringToDate(judgeDto.getFinishTime()).getTime()
                     > NowDate.stringToDate(judgeDto.getDeadTime()).getTime()){
                    offerOrderMapper.updateById(new OfferOrder(oid,6));
                }else{
                    offerOrderMapper.updateById(new OfferOrder(oid,2));
                }

                //更新用户积分
                userMapper.updateWealth(judgeDto.getRuid(),judgeDto.getBounty() * 1.0);
                }
            }
        }
    }

